package com.saodisheng.service.impl;

import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.saodisheng.model.Posts;
import com.saodisheng.model.Tags;
import com.saodisheng.service.AccountService;
import com.saodisheng.service.TagsService;
import com.saodisheng.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * description:
 *
 * @author 扫地生_saodisheng
 * @date 2022/1/28
 */
@Service
public class TagsServiceImpl implements TagsService {
	@Autowired
	private AccountService accountService;

	final Posts postsDao = new Posts().dao();
	final Tags tagsDao = new Tags().dao();
	int pageSize = 15;
	
	@Override
	public List<Posts> getTags() {
		List<Posts> posts = postsDao.findByCache("tag", "tags", "select t.name as tagName, temp.* from "
				+ "(select * from posts order by createAt desc) as temp join tags t on "
				+ "locate(t.name,tags)>0 group by tagName order by createAt desc");
		return posts;
	}
	
	@Override
	public List<Tags> getHotTags(int tagNum) {
		List<Tags> tags = tagsDao.findByCache("hotTag", "hotTag", "select * from tags order by posts desc limit ?", tagNum);
		return tags;
	}
	
	@Override
	public Page<Posts> getPostPageByTag(String tagName, int pageNumber) {
		String select = "select * ";
		String from = "from posts where locate(?,tags)>0 order by createAt desc";
		Page<Posts> postPage = postsDao.paginate(pageNumber, pageSize, select, from, tagName);
		accountService.join("userId", postPage.getList(), "nickName", "avatar");
		return postPage;
	}
	
	@Override
	public Page<Posts> getHotPostPageByTag(String tagName, int pageNumber) {
		String select = "select * ";
		String from = "from posts where locate(?,tags)>0 order by views desc";
		Page<Posts> postPage = postsDao.paginate(pageNumber, pageSize, select, from, tagName);
		accountService.join("userId", postPage.getList(), "nickName", "avatar");
		return postPage;
	}
	
	@Override
	public Ret saveTags(String tags) {
		Ret ret = new Ret();
		ret.setOk();//默认为OK
		if ((tags != null) && (!tags.isEmpty())) {
			String mTags[] = StringUtil.convertStrToArray(tags, ",");
			
			for (String tag : mTags) {
				//数据库中不存在标签才保存
				
				String mTg = Db.queryStr("select name from tags where name=?", tag);
				if (mTg == null) {
					Tags mTag = new Tags();
					//此时文章数1
					mTag.setPosts(1);
					mTag.setName(tag);
					if (!mTag.save()) {
						//失败之后设为fail
						ret.setFail();
					}
				}
				//存在刷新数据
				else {
					Db.update("update tags set posts=posts+1 where name=?", tag);
				}
			}
		}
		return ret;
	}
	
}
